package com.yanq.liancar.activity;
/*
 *  @创建者     Administrator
 *  @创建时间   2018/11/27  10:55
 *  @描述       ${TODO}
 */


import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.ReplyAllAdapter;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.CommentsLikesBean;
import com.yanq.liancar.bean.ReplyAllBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class ReplyAllActivity extends BaseToolbarActivity {
    @BindView(R.id.reply_list)
    RecyclerView replyList;
    @BindView(R.id.headimg)
    CircleImageView headimg;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_commentcontent)
    TextView tvCommentcontent;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_like)
    TextView tvLike;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.et_pinglun)
    EditText etPinglun;
    @BindView(R.id.tv_send)
    TextView tvSend;
    @BindView(R.id.tv_ReplyToPeople)
    TextView tvReplyToPeople;
    @BindView(R.id.ll_pinglun)
    LinearLayout llPinglun;
    private int CommentID, newsID, replytype, objectID;
    private List<ReplyAllBean.DataBean.CommentsRepliesBean> mReplyAllBeans = new ArrayList<>();
    private ReplyAllAdapter mReplyAllAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_replyall);
        ButterKnife.bind(this);
        ImmersionBar.with(this).statusBarColor(R.color.white).statusBarDarkFont(true).init();
        mTvTitle.setText("全部回复");
        CommentID = getIntent().getIntExtra("commentsid", 0);
        getComment();
        initRecyclerview();
        replytype = 1;  //默认回复主评论
    }

    private void initRecyclerview() {
        replyList.setNestedScrollingEnabled(false);
        replyList.setLayoutManager(new LinearLayoutManager(this));
        mReplyAllAdapter = new ReplyAllAdapter(this, mReplyAllBeans);
        replyList.setAdapter(mReplyAllAdapter);

        mReplyAllAdapter.setClickListener(new ReplyAllAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View view) {
                switch (view.getId()) {
                    case R.id.tv_name:
                        replytype = 2;
                        objectID = mReplyAllBeans.get(position).getReplierid();
                        tvReplyToPeople.setText(mReplyAllBeans.get(position).getRepliername());
                        break;
                    case R.id.tv_name1:
                        replytype = 2;
                        objectID = mReplyAllBeans.get(position).getReplierid();
                        tvReplyToPeople.setText(mReplyAllBeans.get(position).getRepliername());
                        break;
                    case R.id.tv_name2:
                        replytype = 2;
                        objectID = mReplyAllBeans.get(position).getReplierid();
                        tvReplyToPeople.setText(mReplyAllBeans.get(position).getObjectname());
                        break;
                }
                // 判断软键盘是否显示
                LogUtils.e("adadada", isSoftShowing() + "");
                if (!isSoftShowing()) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        });
    }

    private boolean isSoftShowing() {
        //获取当前屏幕内容的高度
        int screenHeight = getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        //DecorView即为activity的顶级view
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        //考虑到虚拟导航栏的情况（虚拟导航栏情况下：screenHeight = rect.bottom + 虚拟导航栏高度）
        // 选取screenHeight*2/3进行判断
        return screenHeight * 2 / 3 > rect.bottom;
    }


    @OnClick({R.id.tv_send,R.id.tv_like})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tv_send:
                if (!TextUtils.isEmpty(etPinglun.getText().toString().trim())) {
                    setComment();
                } else {
                    RxToast.info("请输入评论内容");
                }
                break;
            case R.id.tv_like:
                getLikesNum();
                break;
        }

    }

    //获取评论
    private void getComment() {
        OkGo.<String>post(Config.s + "llc/api/select_commentsAll")
                .tag(this)
                .params("commentsid", CommentID + "")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        ReplyAllBean bean = gson.fromJson(response.body(), ReplyAllBean.class);
                        if (bean.isIsSuccess()) {
                            mReplyAllBeans.clear();
                            mReplyAllBeans.addAll(bean.getData().getComments_Replies());
                            mReplyAllAdapter.notifyDataSetChanged();
                            RequestOptions options = new RequestOptions();
                            options.placeholder(R.mipmap.vip_touxiang);
                            Glide.with(mContext).load(bean.getData().getHeadUrl()).apply(options).into(headimg);
                            tvCommentcontent.setText(bean.getData().getCommentscontent());
                            tvTime.setText(bean.getData().getCommentscreatetime());
                            tvLike.setText(bean.getData().getCommentslikesnum() + "");
                            tvComment.setText(bean.getData().getCommentsnum() + "");
                            tvName.setText(bean.getData().getCommentatorname());
                            newsID = bean.getData().getNewsid();
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }
                    }
                });
    }


    //发表评论
    private void setComment() {
        OkGo.<String>post(Config.s + "llc/api/comments_reply")
                .tag(this)
                .params("commentsid", CommentID + "")
                .params("newsid", newsID + "")
                .params("token", UserBean.getcToken(this))
                .params("commentcontent", etPinglun.getText().toString().trim())
                .params("replytype", replytype)
                .params("objectid", objectID)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                        if (bean.isIsSuccess()) {
                            RxToast.success(bean.getOutputMessage());
                            etPinglun.setText("");
                            tvReplyToPeople.setText("");
                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }
                    }
                });
    }

    //评论点赞
    private void getLikesNum(){
        OkGo.<String>post(Config.s + "llc/api/insert_commentsLikes")
                .tag(this)
                .params("newsid", newsID + "")
                .params("commentsid", CommentID + "")
                .params("token", UserBean.getcToken(mContext))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        CommentsLikesBean bean = gson.fromJson(response.body(), CommentsLikesBean.class);
                        if (bean.isIsSuccess()) {
                            if (bean.getCode()==200){
                                tvLike.setText(bean.getData()+"");
                            }else {
                                RxToast.info("操作失败");
                            }
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }
                    }
                });
    }

}
